package com.lonely.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.system.domain.entity.SysSizeLibraryAssociation;
import com.lonely.system.mapper.SysSizeLibraryAssociationMapper;
import com.lonely.system.service.ISysSizeLibraryAssociationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/7/29 9:58
 * @description: 尺码库关联表服务实现类
 */
@Service
public class SysSizeLibraryAssociationServiceImpl extends ServiceImpl<SysSizeLibraryAssociationMapper, SysSizeLibraryAssociation> implements ISysSizeLibraryAssociationService {

    /**
     * 绑定尺码库与尺码的关系
     *
     * @param sizeLibraryId
     * @param sizeIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindSizeLibraryAndSize(Long sizeLibraryId, List<Long> sizeIds) {

        List<SysSizeLibraryAssociation> existsAssociations = super.list(new LambdaQueryWrapper<SysSizeLibraryAssociation>()
                .eq(SysSizeLibraryAssociation::getSizeLibraryId, sizeLibraryId)
        );
        List<Long> existsSizeIds = existsAssociations.stream().map(SysSizeLibraryAssociation::getSizeId).distinct().collect(Collectors.toList());

        // 找出待新增的尺码
        List<Long> needAddSizeIds = CollUtil.subtractToList(sizeIds, existsSizeIds);

        // 找出待删除的尺码
        List<Long> needRemoveSizeIds = CollUtil.subtractToList(existsSizeIds, sizeIds);

        if (CollUtil.isNotEmpty(needAddSizeIds)) {
            super.saveBatch(needAddSizeIds.stream().map(x -> {
                SysSizeLibraryAssociation sysSizeLibraryAssociation = new SysSizeLibraryAssociation();
                sysSizeLibraryAssociation.setSizeId(x);
                sysSizeLibraryAssociation.setSizeLibraryId(sizeLibraryId);
                sysSizeLibraryAssociation.setCreateBy(SecurityUtils.getUserId());
                sysSizeLibraryAssociation.setUpdateBy(SecurityUtils.getUserId());
                return sysSizeLibraryAssociation;
            }).collect(Collectors.toList()));
        }

        if (CollUtil.isNotEmpty(needRemoveSizeIds)) {
            super.remove(new LambdaQueryWrapper<SysSizeLibraryAssociation>()
                    .eq(SysSizeLibraryAssociation::getSizeLibraryId, sizeLibraryId)
                    .in(SysSizeLibraryAssociation::getSizeId, needRemoveSizeIds)
            );
        }

    }
}
